<template>
  <h2>首页</h2>
  <p>count: {{ count }}</p>
  <p>doubleCount: {{ doubleCount }}</p>
  <button @click="fn">count++</button>

  <hr />

  <div>
    <input type="text" v-model="data.username" />
    <input type="text" v-model="data.password" />
  </div>

  <hr />

  <h3>todolist</h3>
  <input type="text" v-model="value" />
  <button @click="add">btn</button>
  <ul>
    <li v-for="item in list" :key="item.id">
      {{ item.name }}
      <button @click="remove(item.id)">删除</button>
    </li>
  </ul>

  <hr />

  <h3>数据请求</h3>
  <ul>
    <li v-for="item in arr" :key="item.id">{{ item.nm }} = {{ item.rt }}</li>
  </ul>

  <hr />

  <h3>event数据类型</h3>
  <input type="text" @input="fn2" />

  <hr />

  <Child :count="count" />
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, provide } from "vue";
import Child from "./Child.vue";

// 不管用ref还是reactive创建变量，都要使用泛型的语法
const count = ref<number>(10);
// const count = ref<number | string>(10);
const fn = (): void => {
  count.value++;
  // count.value = "100";
};

interface DataType {
  username: string;
  password: string;
}
const data = reactive<DataType>({
  username: "zhansan",
  password: "11234",
});

// computed的类型也是通过泛型进行添加
const doubleCount = computed<number>(() => count.value * 2);

// 像watch和生命周期等，如果只是函数调用，没有创建变量，就不需要添加ts类型
watch(count, (): void => {
  console.log("count改变了");
});
onMounted((): void => {
  console.log("页面加载完毕了");
});

interface ListItemType {
  id: number;
  name: string;
}
const value = ref<string>("");
const list = ref<ListItemType[]>([
  {
    id: 1,
    name: "张三",
  },
  {
    id: 2,
    name: "李四",
  },
]);
const add = (): void => {
  list.value.push({
    id: Math.random(),
    name: value.value,
  });
  value.value = "";
};
const remove = (id: number) => {
  list.value = list.value.filter((item) => item.id !== id);
};

interface ArrType {
  id: number;
  nm: string;
  rt: string;
  [propname: string]: any;
}
const arr = ref<ArrType[]>([]);
onMounted((): void => {
  fetch("http://101.35.148.193:3000/api/rated/list")
    .then((response) => response.json())
    .then((res) => {
      arr.value = res.data;
    });
});

const fn2 = (e: Event) => {
  // as叫做断言
  console.log((e.target as HTMLInputElement).value);
};

provide("name", "abc");
</script>
